import {
  Avatar,
  Button,
  Card,
  Divider,
  Empty,
  List,
  message,
  Row,
  Spin,
  Tooltip,
} from 'antd';
import React, { useEffect, useState } from 'react';
import { SyncOutlined, SoundOutlined } from '@ant-design/icons';
import pageStyles from '@/common/pageLayout.less';
import cls from 'classnames';
import { issueAnnounceService } from '../services';
import {
  getColorTextLoadMap,
  getKeyRouter,
  getTimeDistance,
  getUserDepID,
  tooltipLength,
} from '@/utils';
import moment from 'moment';
import listStyles from '../common/styles.less';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { history } from 'umi';
import MyIcon from '@/components/MyIcon';

export const AnnounceView: React.FC<AnnounceHomeAPI.IAnnounceView> = ({
  curRes,
}) => {
  /**
   * 表单 form
   */
  // const [announceTimeForm] = Form.useForm();

  /**
   * 接口回调
   * @param res
   */
  const issueAnnounceCallllback = (res: any) => {
    if (res && res?.msgFlag) {
      // message.success(res?.msg)
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入获取公告接口
   */
  const {
    issueAnnounceData,
    issueAnnounceLoading,
    issueAnnounceRun,
  } = issueAnnounceService(issueAnnounceCallllback);

  /**
   * 时间参数
   */
  // const [defaultTime, setDefaultTime] = useState<any>();

  /**
   * 处理搜索表单时间框默认值
   * @param todayTime 传入的时间
   */
  // const setFormDefault = (todayTime: any) => {
  //   let [startTime, endTime]: any = todayTime;
  //   let time = [startTime, endTime];
  //   announceTimeForm?.setFieldsValue({ announceTime: time });
  // };

  useEffect(() => {
    if (getUserDepID()) {
      let [startTime, endTime]: any = getTimeDistance('month');
      let time = {
        startTime: startTime.format('YYYY-MM-DD 00:00:00'),
        endTime: endTime.format('YYYY-MM-DD 23:59:59'),
      };
      // setFormDefault([startTime, endTime]);
      // setDefaultTime([startTime, endTime])
      getAnnounceData(time);
    }
  }, [getUserDepID()]);

  /**
   * 请求数据
   */
  const getAnnounceData = (time: any) => {
    let payload: any = {
      receiveDeptIds: getUserDepID(),
      ...time,
    };
    issueAnnounceRun(payload);
  };

  //   /**
  //  * 日期框改变
  //  * @param date 改变的日期Moment 格式
  //  * @param dateString string[] 格式
  //  */
  //   const rangeChanage = () => {
  //     if (announceTimeForm?.getFieldsValue()?.announceTime) {
  //       let [
  //         startTime,
  //         endTime,
  //       ]: any = announceTimeForm?.getFieldsValue()?.announceTime;
  //       let time = {
  //         startTime: startTime.format('YYYY-MM-DD 00:00:00'),
  //         endTime: endTime.format('YYYY-MM-DD 23:59:59'),
  //       };
  //       setDefaultTime([startTime, endTime])
  //       getAnnounceData(time);
  //     }
  //   };

  /**
   * 保存当前选中时间节点
   */
  const [saveTimeNode, setSaveTimeNode] = useState<string>('month');

  /**
   * 选择时间搜索
   */
  const searchTimeChange = (timeType: string) => {
    setSaveTimeNode(timeType);
    let [startTime, endTime]: any = getTimeDistance(timeType);
    let time = {
      startTime: startTime.format('YYYY-MM-DD 00:00:00'),
      endTime: endTime.format('YYYY-MM-DD 23:59:59'),
    };
    getAnnounceData(time);
  };

  return (
    <>
      <div style={{ height: '100%', width: '100%' }}>
        <Card
          title={'最新公告'}
          style={{ width: '100%', height: '100%' }}
          bodyStyle={{ padding: 0, height: '85%' }}
          className={cls(pageStyles['page-view'])}
          extra={
            <Row style={{ display: 'flex', alignItems: 'center' }}>
              {/* <Form form={announceTimeForm}>
                <Form.Item name="announceTime" style={{ margin: 0 }}>
                  <RangePicker
                    onChange={rangeChanage}
                    style={{ width: '100%' }}
                    placeholder={['开始时间', '结束时间']}
                    format="YYYY-MM-DD"
                    ranges={{
                      今天: [moment(), moment()],
                      本周: [moment().startOf('week'), moment().endOf('week')],
                      本月: [moment().startOf('month'), moment().endOf('month')],
                      本年: [moment().startOf('year'), moment().endOf('year')],
                    }}
                    // disabledDate={disabledDate}
                    allowClear={false}
                  />
                </Form.Item>
              </Form> */}
              <span>
                <a
                  onClick={() => {
                    searchTimeChange('today');
                  }}
                  style={{
                    fontWeight: saveTimeNode == 'today' ? 600 : 500,
                  }}
                >
                  今天
                </a>
              </span>
              <Divider type="vertical" />
              <span>
                <a
                  onClick={() => {
                    searchTimeChange('week');
                  }}
                  style={{
                    fontWeight: saveTimeNode == 'week' ? 600 : 500,
                  }}
                >
                  本周
                </a>
              </span>
              <Divider type="vertical" />
              <span>
                <a
                  onClick={() => {
                    searchTimeChange('month');
                  }}
                  style={{
                    fontWeight: saveTimeNode == 'month' ? 600 : 500,
                  }}
                >
                  本月
                </a>
              </span>
              <Divider type="vertical" />
              <span>
                <a
                  onClick={() => {
                    searchTimeChange('year');
                  }}
                  style={{
                    fontWeight: saveTimeNode == 'year' ? 600 : 500,
                  }}
                >
                  全年
                </a>
              </span>
              <Divider type="vertical" />
              <Button
                type="primary"
                size="small"
                onClick={() => {
                  let [startTime, endTime]: any = getTimeDistance(saveTimeNode);
                  let time = {
                    startTime: startTime.format('YYYY-MM-DD 00:00:00'),
                    endTime: endTime.format('YYYY-MM-DD 23:59:59'),
                  };
                  getAnnounceData(time);
                }}
              >
                <SyncOutlined />
              </Button>
            </Row>
          }
        >
          <Spin spinning={issueAnnounceLoading}>
            <Row style={{ height: '100%' }}>
              <ScrollBarLayout>
                {issueAnnounceData && issueAnnounceData?.length > 0 ? (
                  <div
                    className={cls(
                      'compile-avatar',
                      listStyles['rightCompileStyle'],
                    )}
                  >
                    <List
                      itemLayout="horizontal"
                      dataSource={issueAnnounceData}
                      renderItem={(item: any) => (
                        <List.Item
                          extra={
                            item?.isTop == 1 ? (
                              <div className={listStyles['iconIsTop']}>
                                <MyIcon type="icon-zhiding" />
                              </div>
                            ) : (
                              <></>
                            )
                          }
                          onClick={() => {
                            history.push({
                              pathname: `/announceController/getIssueAnnounceList/:${getKeyRouter()}${getKeyRouter()}`,
                              state: {
                                id: item?.id,
                              },
                            });
                          }}
                        >
                          <List.Item.Meta
                            avatar={
                              <div>
                                <Avatar size="large" icon={<SoundOutlined />} />
                              </div>
                            }
                            title={
                              <a>
                                <Tooltip
                                  title={tooltipLength(item.announceTitle, 100)}
                                  placement="topLeft"
                                >
                                  <div
                                    style={{
                                      maxWidth: '95%',
                                      display: 'block',
                                      float: 'none',
                                    }}
                                    className={pageStyles['over-flow-hidden']}
                                  >
                                    【
                                    {
                                      getColorTextLoadMap(
                                        item?.announceTypeName,
                                      )?.colorText
                                    }
                                    】{item.announceTitle}
                                  </div>
                                </Tooltip>
                              </a>
                            }
                            description={
                              <Tooltip
                                title={tooltipLength(
                                  item?.announceContent?.contentText,
                                  100,
                                )}
                                placement="topLeft"
                              >
                                <div>
                                  <Row>
                                    <div
                                      style={{ maxWidth: '95%' }}
                                      className={pageStyles['over-flow-hidden']}
                                    >
                                      {item?.announceContent?.contentText}
                                    </div>
                                  </Row>
                                  <Row>
                                    <div
                                      style={{
                                        textAlign: 'right',
                                        width: '100%',
                                        marginTop: '4px',
                                        fontSize: '12px',
                                      }}
                                    >
                                      {moment(item.createTime).format(
                                        'YYYY-MM-DD',
                                      )}
                                    </div>
                                  </Row>
                                </div>
                              </Tooltip>
                            }
                          />
                        </List.Item>
                      )}
                    />
                  </div>
                ) : (
                  <div
                    style={{
                      width: '100%',
                      height: '100%',
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                    }}
                  >
                    <Empty
                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                      description="暂无数据"
                    />
                  </div>
                )}
              </ScrollBarLayout>
            </Row>
          </Spin>
        </Card>
      </div>
    </>
  );
};
